<?php
/**
 * 汇友科技
 * @copyright (c) 2017 http://www.huiyou365.net All rights reserved.
 * @author: Creatint <creatint@163.com>
 */

namespace Admin\Model;

use Common\Model\Model;
use Think\Page;
use Common\Contract\Position as PositionContract;

class ItemModel extends Model{
    protected $error = null;
    private $lists = null;
    private $page = null;
    protected $data = null;

    protected $_validate = array(
        array('name','/^[a-zA-Z]\w{0,39}$/','标识不合法',self::VALUE_VALIDATE,'regex',self::MODEL_BOTH),
        array('name','','标识已存在',self::VALUE_VALIDATE,'unique',self::MODEL_BOTH),
        array('title','require','名称不能为空',self::MUST_VALIDATE,'regex',self::MODEL_BOTH),
        array('title','3,50','名称长度在3~50之间',self::MUST_VALIDATE,'length',self::MODEL_BOTH),
        array('uid','require','用户ID不能为空',self::EXISTS_VALIDATE,'regex',self::MODEL_INSERT),
        array('did','require','地区ID不能为空',self::MUST_VALIDATE,'regex',self::MODEL_INSERT),
        array('phone','6,20','请输入合法的电话号码',self::VALUE_VALIDATE,'length',self::MODEL_BOTH),
        array('description', '1,500', '描述长度不能超过500个字符', self::VALUE_VALIDATE, 'length', self::MODEL_BOTH),
        array('status','0,1,2','状态不正确',self::VALUE_VALIDATE,'in',self::MODEL_BOTH),
//        array('status_json','check_status_json','状态JSON不正确',self::VALUE_VALIDATE,'callback',self::MODEL_BOTH),
    );

    protected $_auto = array(
        array('position','get_position',self::MODEL_BOTH,'callback'),
        array('updated_at',NOW_TIME,self::MODEL_BOTH),
        array('created_at',NOW_TIME,self::MODEL_INSERT),
    );


    /**
     * 获取列表，原生数据.
     *
     * @param null $query
     * @param bool $field 需要的字段
     * @param bool $showPage 是否显示分页数据
     * @return mixed
     */
    public function get($query = null, $field = true, $order = '', $showPage = true, Closure $closure = null ){
        $order || $order = $this->id . ' DESC';
        $map = [];
        if ($query !== null) {
            foreach ($query as $key => $value) {
                if ($value !== null) {
                    $map[$key] = $value;
                }
            }
        }

        // 是否显示分页数据
        if ( $showPage ) {
            $res = $this
                ->where($map)
                ->order($order)
                ->page(I('get.p',0) . ',' . C('LIST_ROWS'))
                ->field($field)
                ->select();
            $count = $this->where($map)->count();
            $this->page = show_page(new Page($count, C('LIST_ROWS')));
        } else {
            $res = $this
                ->where($map)
                ->order($order)
                ->field($field)
                ->select();
        }

        // 其他处理
        if ( $closure ) {
            $res = $closure($res);
        }

        return $res;
    }



	public function getPage() {
		return $this->page;
	}

    public function getError(){
        return $this->error;
    }

    public function check_description($description){
        return true;
    }
    public function get_district(){
        if ( $this->did ){
            $districts = S('districts');
            return $districts[$this->did]['title'];
        } else {
            return false;
        }
    }

    public function get_status_json(){
        $status_arr = json_decode($this->status_json, true);
        $years = array_flip(array_column($status_arr,'year'));
        if ( empty($years[date('Y')]) ) {
            $status_arr[] = array('year'=>date('Y'),'status'=>$this->status);
        } else {
            $status_arr[$years[date('Y')]]['status'] = $this->status;
        }
        return json_encode($status_arr);
    }

    public function get_position($pos){
        if ($pos)
            $this->position = $pos;
        if ( !is_array($this->position) ){
            return 0;
        } else {
            $pos = 0;
            foreach ( $this->position as $k=>$v ){
                $pos += $v;
            }
            return $pos;
        }
    }

    public function remove($id, $real = false){
        if ( !$id ) {
            $this->error = '待删除项为空';
            return false;
        }

        $map = [];

        if (is_array($id)) {
			$map['id'] = ['in', $id];
        } else {
            if (is_numeric($id)) {
                $id = (array)(int)$id;
            } else if ( is_string($id) && strpos($id, ',') > 0) {
                $id = preg_split('/[,，;\r\n]+/', trim($id, ",，;\r\n"));
            }

            $map = [
                'id'=>[
                    'IN',
                    $id
                ]
            ];
        }



        if ( !$id ) {
            $this->error = '待删除项为空';
            return false;
        }

		if ($real === false) {
			if ( $this->where($map)->setField('status', -1) ) {
				return true;
			} else {
				return false;
			}
		} else {
			if ( $this->where($map)->delete() ) {
				return true;
			} else {
				return false;
			}
		}

    }


    public function restore($id){
        if ( !$id ) {
            $this->error = '待还原项为空';
            return false;
        }

        $map = [];

        if (is_array($id)) {
            $map = [
                'id'=>[
                    'IN',
                    $id
                ]
            ];
        } else {
            if (is_numeric($id)) {
                $id = (array)(int)$id;
            } else if ( is_string($id) && strpos($id, ',') > 0) {
                $id = preg_split('/[,，;\r\n]+/', trim($id, ",，;\r\n"));
            }

            $map = [
                'id'=>[
                    'IN',
                    $id
                ]
            ];
        }



        if ( !$id ) {
            $this->error = '待还原项为空';
            return false;
        }
			if ( $this->where($map)->setField('status', 0) ) {
				return true;
			} else {
				return false;
			}

    }
}
